const db = require("../db/index");

//获取全部知识库
exports.getallcategory = (req, res) => {
  const sql = "select * from storehouse where status = 1 order by id asc";
  db.query(sql, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常",
      });
    res.send({
      code: 200,
      message: "获取知识库成功",
      data: result,
    });
  });
};

//获取最近新增知识库
exports.getnewcategory = (req, res) => {
  const sql =
    "select * from storehouse where status = 1 order by createdate desc";
  db.query(sql, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常",
      });
    res.send({
      code: 200,
      message: "获取最新知识库成功",
      data: result.slice(0, 7),
    });
  });
};

//新增知识库
exports.addcategory = (req, res) => {
  if (
    req.body.storename.length < 1 ||
    req.body.briefly.length < 1 ||
    req.body.storename.length > 10 ||
    req.body.briefly.length > 50
  )
    return res.send({
      code: 1001,
      message: "参数格式不合法",
    });
  const sql = "select * from storehouse where storename = ? ";
  db.query(sql, [req.body.storename], (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常",
      });
    if (result.length === 1)
      return res.send({
        code: 1002,
        message: "知识库名已被占用,请更换后重试",
      });
    const sqlstr = "insert into storehouse set ?";
    req.body.founderid = req.user.id;
    db.getConnection(function (err, connection) {
      if (err) {
        return res.send({
          code: 1003,
          message: "数据库异常",
        });
      }
      connection.beginTransaction((err) => {
        //开启事务
        if (err) {
          return res.send({
            code: 1003,
            message: "数据库异常",
          });
        } else {
          connection.query(sqlstr, req.body, (e, result1) => {
            if (e) {
              res.send({ code: 1003, message: "创建失败，请稍后重试" });
              return connection.rollback(() => {
                console.log("插入失败数据回滚"+e);
              });
            } else {
              let param = {
                storeid: result1.insertId,
                memberid: req.user.id,
                isfounder: 1,
              };
              const sql3 = "insert into storemember set ?";
              connection.query(sql3, param, (e, result2) => {
                if (e) {
                  res.send({ code: 1003, message: "创建失败，请稍后重试" });
                  return connection.rollback(() => {
                    console.log("插入失败数据回滚");
                  });
                } else {
                  connection.commit((error) => {
                    if (error) {
                      console.log("事务提交失败");
                    }
                  });
                  connection.release(); // 释放链接

                  return res.send({
                    code: 200,
                    message: "插入成功",
                    id: result1.insertId,
                    success: true,
                  }); // 返回数据库操作结果这里数据格式可根据个人或团队规范来定制
                }
              });
            }
          });
        }
      });
    });
  });
};

//根据id获取文章分类
exports.getsomecategory = (req, res) => {
  req.params.id = parseInt(req.params.id);
  if (Number.isNaN(req.params.id))
    return res.send({
      code: 1001,
      message: "参数不合法",
    });
  const sql =
    "select storehouse.*,user.username as foundername,user.face as founderface from storehouse , user where storehouse.status = 1 and storehouse.id = ? and user.id  = storehouse.founderid ";
  db.query(sql, req.params.id, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
    res.send({
      code: 200,
      message: "获取该分类成功",
      data: result,
    });
  });
};
//根据id更新知识库数据
exports.updatecate = (req, res) => {
  const body = req.body;
  if (body.storename.length < 1 || body.storename.length > 30)
    return res.send({
      code: 1001,
      message: "分类名长度异常",
    });
  if (body.briefly.length < 1 || body.briefly.length > 150)
    return res.send({
      code: 1001,
      message: "简介长度异常",
    });
  console.log(body.founderid, req.user.id);
  if (body.founderid != req.user.id)
    return res.send({ code: 401, message: "暂无权限" });
  const sql = `update storehouse set ? where id = ?`;
  db.query(sql, [body, body.id], (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常",
      });
    if (result.affectedRows !== 1)
      return res.send({
        code: 1002,
        message: "更新知识库失败",
      });
    res.send({
      code: 200,
      message: "更新知识库成功",
    });
  });
};
// 加入知识库
exports.joinStore = (req, res) => {
  let param = {
    storeid: req.params.id,
    memberid: req.user.id,
    isfounder: 0,
  };
  const sql = "insert into storemember set ?";
  db.query(sql, param, (err) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常",
      });
    else {
      return res.send({
        code: 200,
        message: "加入成功",
      });
    }
  });
};
//获取知识库成员
exports.getStoreMember = (req, res) => {
  const sql =
    "select storemember.isfounder,user.id,user.username,user.face from storemember,user where storemember.storeid = ? and storemember.memberid = user.id order by storemember.id asc";
  db.query(sql, req.params.id, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常",
      });
    return res.send({
      code: 200,
      data: result,
    });
  });
};
//查找知识库直属所有文件
exports.getStoreFile = (req, res) => {
  const sql =
    "select storefiles.*,user.username from storefiles,user where storefiles.storeid = ? and storefiles.isprivate = 0 and storefiles.status = 1 and user.id = storefiles.founderid order by storefiles.createdate desc";
  db.query(sql, [req.params.id], (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常",
      });
    return res.send({
      code: 200,
      data: result,
    });
  });
};
// 上传附件/新建文件夹
exports.uploadFiles = (req, res) => {
  let param = {
    filetitle: req.body.title,
    type: req.body.type,
    typeid: req.body.type === 3 ? req.body.typeid : null,
    parentid: req.body.parentid,
    storeid: req.body.storeid,
    founderid: req.user.id,
  };
  const sql1 = "select * from storemember where storeid = ? and memberid = ?";
  db.query(sql1, [req.body.storeid, req.user.id], (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常",
      });
    if (result.length < 1) {
      return res.send({
        code: 403,
        message: "您没有权限，请先加入该库",
      });
    }
    const sql2 = "insert into storefiles set ?";
    db.query(sql2, param, (err) => {
      if (err)
        return res.send({
          code: 500,
          message: "数据库异常",
        });
      else {
        return res.send({
          code: 200,
          message: "新建成功",
        });
      }
    });
  });
};

//删除文件
exports.deleteFile = (req, res) => {
  const sql = "select * from storefiles where id = ?";
  db.query(sql, req.body.id, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
    if (result[0].founderid != req.user.id)
      return res.send({
        code: 403,
        message: "无权限删除他人文件",
      });
    const sqlstr =
      req.body.type !== 2
        ? "update storefiles set status = 0 where id = ?"
        : "update storefiles set status = 0 where id = ? or parentid = ?";
    db.query(sqlstr, [req.body.id, req.body.id], (err, result) => {
      if (err)
        return res.send({
          code: 500,
          message: "数据库异常" + err.message,
        });
      if (result.affectedRows < 1)
        return res.send({
          code: 1002,
          message: "删除文件失败",
        });
      res.send({
        code: 200,
        message: "删除文件成功",
      });
    });
  });
};

// 更改文件夹名字
exports.updateFileName = (req, res) => {
  const sql0 = "select * from storefiles where where id = ?";
  db.query(sql0, req.body.id, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常",
      });
    if (result[0].founderid != req.user.id) {
      return res.send({
        code: 403,
        message: "无权限更改他人文件",
      });
    }
    const sql = "update storefiles set filetitle = ? where id = ?";
    db.query(sql, [req.body.filetitle, req.body.id], (err, result) => {
      if (err)
        return res.send({
          code: 500,
          message: "数据库异常",
        });
      if (result.affectedRows < 1)
        return res.send({
          code: 1002,
          message: "重命名失败",
        });
      else {
        return res.send({
          code: 200,
          message: "重命名成功",
        });
      }
    });
  });
};
// 迁移知识库文件
exports.moveFile = (req, res) => {
  const sql = "update storefiles set parentid = ? where id = ?";
  db.query(sql, [req.body.moveTo, req.body.id], (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常",
      });
    if (result.affectedRows < 1)
      return res.send({
        code: 1002,
        message: "迁移失败",
      });
      else {
        return res.send({
          code: 200,
          message: "迁移成功",
        });
      }
  });
};
